package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	@Autowired
	private CustomerRepository customerRepository;

	@Override
	public List<Customer> findNoAssociation() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findAssociation(String customerFixedAreaId) {
		return customerRepository.findByFixedAreaId(customerFixedAreaId);
	}

	@Override
	public void updateAssociation(String customerFixedAreaId, String customerIdStr) {
		customerRepository.clearAssocaition(customerFixedAreaId);
		if (customerIdStr == null || StringUtils.isBlank(customerIdStr)) {
			return;
		}
		String[] st = customerIdStr.split(",");
		for (String cid : st) {
			Integer customerId = Integer.parseInt(cid);
			customerRepository.updateAssocaition(customerFixedAreaId, customerId);
		}
	}

	@Override
	public void addCustomer(Customer customer) {
		customerRepository.save(customer);
	}

	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone, password);
	}

	@Override
	public String findFixedAreaId(String address) {
		return customerRepository.findFixedAreaIdByAddress(address);
	}

}
